package role

import (
	"context"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RoleMenuActionBindLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRoleMenuActionBindLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleMenuActionBindLogic {
	return &RoleMenuActionBindLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// RoleMenuActionBind 角色绑定菜单和功能，请求时传全量绑定数据
func (l *RoleMenuActionBindLogic) RoleMenuActionBind(req *types.RoleMenuActionBindRo) (resp *types.BaseRsp, err error) {
	if err := l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.RoleId).
		First(&model.RoleConfig{}).Error; err != nil {
		return nil, errors.Wrap(err, "角色不存在")
	}
	for _, menu := range req.MenuActions {
		if err := l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", menu.MenuId).
			First(&model.MenuConfig{}).Error; err != nil {
			return nil, errors.Wrap(err, "菜单不存在")
		}
		for _, action := range menu.ActionId {
			if err := l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", action).
				First(&model.ActionConfig{}).Error; err != nil {
				return nil, errors.Wrap(err, "功能不存在")
			}
		}
	}

	err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
		// 先删除
		if err := tx.Where("RoleId=?", req.RoleId).Delete(&model.RoleMenuAction{}).
			Error; err != nil {
			return err
		}
		// 再插入
		for _, menu := range req.MenuActions {
			for _, action := range menu.ActionId {
				if err := tx.Create(&model.RoleMenuAction{
					RoleId:   req.RoleId,
					MenuId:   menu.MenuId,
					ActionId: action,
				}).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})

	return
}
